package com.czeczek.domain.dao.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;

import com.czeczek.domain.IndicatorDim;
import com.czeczek.domain.IndicatorParamDim;

public class IndicatorsMapper implements RowMapper<IndicatorDim> {
	
	private final static int INDICATOR_ID = 1;
	private final static int INDICATOR_NAME = 2;
	private final static int INDICATOR_CLASS_NAME = 3;
	private final static int INDICATOR_PARAMETER_NAME = 4;
	private final static int INDICATOR_PARAMETER_VALUE = 5;
		
	private Map<Long, IndicatorDim> indicators;
	
	public IndicatorsMapper() {
		indicators = new HashMap<Long, IndicatorDim>();
	}

	public IndicatorDim mapRow(ResultSet rs, int rowNum) throws SQLException {
		IndicatorDim indicator = null;
		IndicatorParamDim param = null;
		
		long id = rs.getLong(INDICATOR_ID);
		String paramName = rs.getString(INDICATOR_PARAMETER_NAME);
		
		if (paramName != null) {
			param = new IndicatorParamDim();
			param.setIndicatorId(id);
			param.setName(rs.getString(INDICATOR_PARAMETER_NAME));
			param.setValue(rs.getBigDecimal(INDICATOR_PARAMETER_VALUE));
		}
		
		if (indicators.containsKey(id)) {
			indicator = indicators.get(id);
			if (param != null) {
				indicator.getParameters().add(param);
			}
		} else {
			indicator = new IndicatorDim();
			indicator.setId(id);
			indicator.setName(rs.getString(INDICATOR_NAME));
			indicator.setClassName(rs.getString(INDICATOR_CLASS_NAME));
			if (param != null) {
				indicator.getParameters().add(param);
			}
			indicators.put(id, indicator);
		}
		
		return indicator;
	}
	
	
	public List<IndicatorDim> getIndicators() {
		return new ArrayList<IndicatorDim>(indicators.values());
	}

}
